package com.pw.study.flink.chapter3;

import com.pw.study.flink.entities.Market;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class AppMarket {

    public static void main(String[] args) {
        dealApp();
    }

    private static void dealApp() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.addSource(new MyAppSource()).map(new MapFunction<Market, Tuple2<String,Long>>() {
                    @Override
                    public Tuple2<String, Long> map(Market market) throws Exception {
                        return Tuple2.of(market.getChannel()+"_"+market.getBehavior(),1L);
                    }
                })
                .keyBy(t->t.f0).sum(1).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyAppSource extends RichSourceFunction<Market> {
        List<String> channels = Arrays.asList("huawwei", "xiaomi", "apple", "baidu", "qq", "oppo", "vivo");
        List<String> behaviors = Arrays.asList("download", "install", "update", "uninstall");

        @Override
        public void run(SourceContext<Market> out) throws Exception {
            Random rd = new Random();
            while (true) {
                Long userId = Long.valueOf(rd.nextInt(1000) + 1000);
                String behavior = behaviors.get(rd.nextInt(behaviors.size()));
                String channel = channels.get(rd.nextInt(channels.size()));
                Long ts = Long.valueOf(rd.nextInt(2000) + 10000);
                Market market = new Market(userId, behavior, channel, ts);
                out.collect(market);
                Thread.sleep(300);
            }

        }

        @Override
        public void cancel() {

        }
    }
}
